import axios from "axios";
import {getToken} from "@/utils/auth";
import cache from "@/plugins/cache";
import {tansParams} from "@/utils/zpPlatform";
import errorCode from "@/utils/errorCode";
import "element-plus/theme-chalk/el-message.css";
import "element-plus/theme-chalk/el-message-box.css";
import {useUserStoreHook} from "@/store/modules/user";
//引入loading

// // 全局loading相关代码
let loading: any; //定义loading变量
const options: any = {
  lock: true,
  text: "拼命加载中...",
  spinner: 'loading',
  background: "rgba(3,3,3,0.7)",
  fullscreen: true,
};

//创建loading
// function startLoading() {
//   loading = ElLoading.service(options);
//   // loading最少显示时间（为了防止当请求立马响应页面会闪一下的情况）
//   return new Promise<void>((resolve) => {
//     setTimeout(() => {
//       resolve();
//     }, 300);
//   });
// }

//清除loading
// async function endLoading() {
//   await startLoading();
//   loading.close();
// }

//记录当前需要显示加载动画的请求数量
let needLoadingRequestCount = 0;
//使用防抖函数防止重复创建和清理loading的问题
// const showFullScreenLoading = debounce(
//   () => {
//     if (needLoadingRequestCount === 0) {
//       startLoading();
//     }
//     needLoadingRequestCount++;
//   },
//   500,
//   true
// );

// const tryHideFullScreenLoading = debounce(
//   () => {
//     if (needLoadingRequestCount <= 0) return;
//     needLoadingRequestCount--;
//     if (needLoadingRequestCount === 0) {
//       endLoading().then((_r) => {
//       });
//     }
//   },
//   400,
//   true
// );

// 是否显示重新登录
export const isRelogin = {show: false};


const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  //@ts-ignore
  baseURL: import.meta.env.VITE_APP_TARGET_URL,
  timeout: 1000 * 120,
  withCredentials: false,
});

let loadingInstance: any;

service.interceptors.request.use(
  (config: any) => {
    // if (config.url != '/code' && config.url != '/system/login' && config.url != '/system/logout'
    //   && config.url.search("/sysUserMessage/listSysUserMessageMap") <= -1
    //   && config.url.search("autoBuildQuery") <= -1
    //   && config.url.search("autoPrescriptionList") <= -1
    //   && config.url.search("getAutoDrugPriceInfo") <= -1
    //   && config.url.search("autoExportList") <= -1
    //   && config.url.search("getAutoHisIcd") <= -1
    // ) {
    //   showFullScreenLoading();
    // }
    config.params = config.params || {}

    const useUserStore = useUserStoreHook();
    const user = useUserStore.user
    if (getToken()) {
      config.headers.Authorization = "Bearer " + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    // get请求映射params参数
    if (config.method === "get" && config.params) {
      if (user.userInfo) {
        config.params.userLoginId = user.userInfo.userId
        if (user.currentSelectDept) {
          config.params.deptLoginId = user.currentSelectDept
        }
      }
      let url = config.url + "?" + tansParams(config.params);
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    if (config.method === "post" || config.method === "put") {
      config.data = config.data || {}
      if (user.userInfo) {
        config.data.userLoginId = user.userInfo.userId
        if (user.currentSelectDept) {
          config.data.deptLoginId = user.currentSelectDept
        }
      }
      const requestObj = {
        url: config.url,
        data:
          typeof config.data === "object"
            ? JSON.stringify(config.data)
            : config.data,
        time: new Date().getTime(),
      };
      const sessionObj = cache.session.getJSON("sessionObj");
      if (sessionObj === undefined || sessionObj === null) {
        cache.session.setJSON("sessionObj", requestObj);
      } else {
        const s_url = sessionObj["url"]; // 请求地址
        const s_data = sessionObj["data"]; // 请求数据
        const s_time = sessionObj["time"]; // 请求时间
        const interval = 1000; // 间隔时间(ms)，小于此时间视为重复提交
        if (
          s_data === requestObj.data &&
          requestObj.time - s_time < interval &&
          s_url === requestObj.url
        ) {
          const message = "数据正在处理，请勿重复提交";
          console.warn(`[${s_url}]: ` + message);
          return Promise.reject(new Error(message));
        } else {
          cache.session.setJSON("sessionObj", requestObj);
        }
      }
    }
    return config;
  },
  (error) => {
    // 关闭加载动画
    // tryHideFullScreenLoading();
    Promise.reject(error);
  }
);
service.interceptors.response.use(
  (res: any) => {
    // if (res.config.url != '/code' && res.config.url != '/system/login' && res.config.url != '/system/logout'
    //   && res.config.url.search("/sysUserMessage/listSysUserMessageMap") <= -1
    //   && res.config.url.search("autoBuildQuery") <= -1
    //   && res.config.url.search("autoPrescriptionList") <= -1
    //   && res.config.url.search("getAutoDrugPriceInfo") <= -1
    //   && res.config.url.search("autoExportList") <= -1
    //   && res.config.url.search("getAutoHisIcd") <= -1
    // ) {
    //   tryHideFullScreenLoading();
    // }
    const useUserStore = useUserStoreHook();
    const data = res.data;
    // SecretDataFn(data)
    // 未设置状态码则默认成功状态
    const code = data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || data.msg || errorCode.default;
    if (res.status === 200 && print(res)) {
      return {}
    }
    // 二进制数据则直接返回
    if (
      res.headers["content-type"] === "application/octet-stream" ||
      res.request.responseType === "blob" ||
      res.request.responseType === "arraybuffer"
    ) {
      return res;
    }
    if (
      res.request.responseURL.indexOf("getNucleicAcid") >= 0 ||
      res.request.responseURL.indexOf("getHealthInfoLevel") >= 0
    ) {
      return data;
    }
    if (code === 401) {
      if (!isRelogin.show) {
        isRelogin.show = true;
        ElMessageBox.confirm(
          "登录状态已过期，您可以继续留在该页面，或者重新登录",
          "系统提示",
          {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            isRelogin.show = false;
            useUserStore.LogOut().then(() => {
              location.href = 8080 + "#/login";
            });
          })
          .catch(() => {
            isRelogin.show = false;
          });
      }
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
    } else if (code === 500) {
      ElMessage({
        message: msg,
        type: "error",
      });
      return Promise.reject(new Error(msg));
    } else if (code !== 200) {
      ElNotification.error({
        title: msg,
      });
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject("error");
    } else {
      return data;
    }
  },
  (error) => {
    // 关闭加载动画
    // endLoading().then((_r) => {
    // });
    let {message} = error;
    if (message === "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      // message = "系统接口请求超时";
      return {message: message};
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    ElMessage({
      message: message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);


function print(response) {
  // 判断后端是否返回文件流，若是则下载文件
  const headers = response.headers
  if (headers && headers['content-type'] && headers['content-type'].indexOf('application/pdf') > -1) {// 判断返回文件流
    const url = window.URL.createObjectURL(new Blob([response.data], {'type': 'application/pdf'}))
    let iframe = document.getElementById('print_preview') as any
    if (iframe === null) {
      let iframe = document.createElement('iframe') as any
      document.body.appendChild(iframe)
      iframe.setAttribute('id', 'print_preview')
      iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:0px;top:0px;')
      iframe.setAttribute('src', url)
      iframe.onload = function () {
        iframe.contentWindow.print()
      }
    } else {
      iframe.setAttribute('src', url)
      iframe.onload = function () {
        iframe.contentWindow.print()
      }
    }
    return true
  }
  return false
}

/**
 * http握手错误
 * @param result 响应回调,根据不同响应进行不同操作
 */
// function errorHandle(result: any) {
//   switch (result.code) {
//     case 50011:
//       setTimeout(() => {
//         store.dispatch("setOutin", {});
//         router.push({
//           path: "/login",
//           query: {
//             T: new Date().getTime(),
//           },
//         });
//       }, 1500);
//       ElNotification({
//         title: "提示",
//         message: result.msg,
//         type: "warning",
//       });
//       break;
//     case 50010:
//       setTimeout(() => {
//         store.dispatch("setOutin", {});
//         router.push({
//           path: "/login",
//           query: {
//             T: new Date().getTime(),
//           },
//         });
//       }, 1500);
//       ElNotification({
//         title: "提示",
//         message: result.msg,
//         type: "warning",
//       });
//       break;
//     case 50012:
//       setTimeout(() => {
//         store.dispatch("setOutin", {});
//         router.push({
//           path: "/login",
//           query: {
//             T: new Date().getTime(),
//           },
//         });
//       }, 1500);
//       ElNotification({
//         title: "提示",
//         message: result.msg,
//         type: "warning",
//       });
//       break;
//     case 403:
//       break;
//     default:
//       ElNotification({
//         title: "提示",
//         message: "异常错误！",
//         type: "warning",
//       });
//   }
// }

/**
 * get请求
 * @param params 参数
 * @param jwt  是否token校验
 * @param url  接口
 */
export const getData = (url: string, params: any, isJwt: boolean) => {
  const headers = {isJwt: isJwt};
  return new Promise((resolve, reject) => {
    service
      .get(url, {
        headers: headers,
        params: params,
      })
      .then((response: any) => {
        resolve(response);
      })
      .catch((error: any) => {
        reject(error.msg);
      });
  });
};

/**
 * post请求
 * @param params 参数
 * @param jwt  是否token校验
 * @param url   接口
 */
export const postData = (url: string, params: any, isJwt: boolean) => {
  const headers = {isJwt: isJwt};
  return new Promise((resolve, reject) => {
    service
      .post(url, params, {
        headers: headers,
      })
      .then((response: any) => {
        resolve(response);
      })
      .catch((error: any) => {
        reject(error.msg);
      });
  });
};
export default service;
